package com.aiguigu.gulimall.ssoclient2.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname HelloController
 * @Description TODO
 * @Date 2021/9/18 14:32
 * @Author Anonymous
 */
@SuppressWarnings("all")
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String url;//取出配置文件中的值

    /**
     * 无需登录就可以访问
     */
    @GetMapping("/hello")
    public String hello() {
        System.out.println("Hello ===================");
        return "Hello";
    }

    /**
     * 需要登录才能访问
     * 要具备一个能力：感知这次是在ssoserver登录成功跳回来的，而不是我们直接访问你的
     */
    @RequestMapping("/boss")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            //去ssoserver登录成功就会带上
            //TODO 1、去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();//模拟发请求
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser", body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //没登录,跳转到登录服务器登录
            return "redirect:" + url + "?redirect_url=http://client2.com:8082/boss";
        } else {

        }
        List<String> campus = new ArrayList<>();
        campus.add("henu");
        campus.add("swjtu");
        campus.add("bd");
        model.addAttribute("campus", campus);
        return "list";
    }
}
